package com.hk.huakangcompany.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/15 17:54
 * @Statement: 跨域
 */
@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsFilter corsFilter() {
//        获取CorsFilter配置信息
        CorsConfiguration configuration = new CorsConfiguration();
//        添加所允许的域
        configuration.addAllowedOrigin("http://manage.hk.com");
        configuration.addAllowedOrigin("http://127.0.0.1:9001");
        configuration.addAllowedOrigin("http://localhost:9001");
        configuration.addAllowedOrigin("http://localhost:9003");
//        允许携带Cookie
        configuration.setAllowCredentials(true);
//        允许请求方式
        configuration.addAllowedMethod(HttpMethod.GET);
        configuration.addAllowedMethod(HttpMethod.OPTIONS);
        configuration.addAllowedMethod(HttpMethod.POST);
        configuration.addAllowedMethod(HttpMethod.PUT);
        configuration.addAllowedMethod(HttpMethod.DELETE);
        configuration.addAllowedMethod(HttpMethod.PATCH);
        configuration.addAllowedMethod(HttpMethod.HEAD);
//        允许的头信息
        configuration.addAllowedHeader("*");
//        允许有效时长(一小时)
        configuration.setMaxAge(3600L);
//        添加映射路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",configuration);
//        返回新的CrosFilter
        return new CorsFilter(source);
    }

}
